/**
 * Axios请求工具类
 * 模拟Axios的请求封装，提供拦截器、请求模板等功能
 */

/**
 * Axios客户端类
 */
class AxiosClient {
  constructor(config = {}) {
    this.baseURL = config.baseURL || '';
    this.timeout = config.timeout || 10000;
    this.headers = config.headers || {};
    this.withCredentials = config.withCredentials || false;
    this.interceptors = config.interceptors || [];
    this.templates = config.templates || {};
  }

  /**
   * 添加拦截器
   */
  addInterceptor(interceptor) {
    this.interceptors.push(interceptor);
  }

  /**
   * 添加请求模板
   */
  addTemplate(name, template) {
    this.templates[name] = template;
  }

  /**
   * 获取请求模板
   */
  getTemplate(name) {
    return this.templates[name];
  }

  /**
   * 执行请求拦截器
   */
  async executeRequestInterceptors(config) {
    let finalConfig = { ...config };

    for (const interceptor of this.interceptors) {
      if (interceptor.request) {
        finalConfig = await interceptor.request(finalConfig);
      }
    }

    return finalConfig;
  }

  /**
   * 执行响应拦截器
   */
  async executeResponseInterceptors(response) {
    let finalResponse = response;

    for (const interceptor of this.interceptors) {
      if (interceptor.response) {
        finalResponse = await interceptor.response(finalResponse);
      }
    }

    return finalResponse;
  }

  /**
   * 执行错误拦截器
   */
  async executeErrorInterceptors(error) {
    for (const interceptor of this.interceptors) {
      if (interceptor.error) {
        try {
          return await interceptor.error(error);
        } catch (e) {
          // 继续执行下一个拦截器
        }
      }
    }
    throw error;
  }

  /**
   * 发送请求
   */
  async request(config) {
    try {
      // 处理URL
      const url = config.url.startsWith('http') ? config.url : this.baseURL + config.url;

      // 合并配置
      const finalConfig = {
        ...config,
        url,
        timeout: config.timeout || this.timeout,
        headers: { ...this.headers, ...config.headers },
        withCredentials: config.withCredentials ?? this.withCredentials
      };

      // 执行请求拦截器
      const processedConfig = await this.executeRequestInterceptors(finalConfig);

      // 发送请求
      const response = await this.sendRequest(processedConfig);

      // 执行响应拦截器
      return await this.executeResponseInterceptors(response);
    } catch (error) {
      // 执行错误拦截器
      return await this.executeErrorInterceptors(error);
    }
  }

  /**
   * 实际发送请求
   */
  async sendRequest(config) {
    const { url, method = 'GET', headers = {}, data, timeout = 10000 } = config;

    // 构建请求配置
    const fetchConfig = {
      method,
      headers: new Headers(headers),
      credentials: config.withCredentials ? 'include' : 'same-origin'
    };

    // 添加请求体
    if (data) {
      if (data instanceof FormData) {
        fetchConfig.body = data;
      } else if (typeof data === 'object') {
        fetchConfig.headers.set('Content-Type', 'application/json');
        fetchConfig.body = JSON.stringify(data);
      } else {
        fetchConfig.body = data;
      }
    }

    // 创建超时控制器
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    fetchConfig.signal = controller.signal;

    try {
      const response = await fetch(url, fetchConfig);
      clearTimeout(timeoutId);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const responseData = await this.parseResponse(response, config);
      const responseHeaders = {};
      response.headers.forEach((value, key) => {
        responseHeaders[key] = value;
      });

      return {
        data: responseData,
        status: response.status,
        statusText: response.statusText,
        headers: responseHeaders,
        config
      };
    } catch (error) {
      clearTimeout(timeoutId);
      throw error;
    }
  }

  /**
   * 解析响应数据
   */
  async parseResponse(response, config) {
    const responseType = config.responseType || 'json';

    switch (responseType) {
      case 'json':
        return await response.json();
      case 'text':
        return await response.text();
      case 'blob':
        return await response.blob();
      case 'arraybuffer':
        return await response.arrayBuffer();
      default:
        return await response.text();
    }
  }

  /**
   * GET请求
   */
  async get(url, params, config) {
    const queryString = params ? '?' + new URLSearchParams(params).toString() : '';
    return this.request({
      ...config,
      url: url + queryString,
      method: 'GET'
    });
  }

  /**
   * POST请求
   */
  async post(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'POST',
      data
    });
  }

  /**
   * PUT请求
   */
  async put(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'PUT',
      data
    });
  }

  /**
   * DELETE请求
   */
  async delete(url, config) {
    return this.request({
      ...config,
      url,
      method: 'DELETE'
    });
  }

  /**
   * PATCH请求
   */
  async patch(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'PATCH',
      data
    });
  }

  /**
   * 使用模板发送请求
   */
  async requestByTemplate(templateName, data, config) {
    const template = this.getTemplate(templateName);
    if (!template) {
      throw new Error(`Template '${templateName}' not found`);
    }

    return this.request({
      ...template,
      ...config,
      data: data || template.data
    });
  }

  /**
   * 分页请求
   */
  async pageRequest(url, pageParams, config) {
    const params = {
      page: pageParams.page,
      pageSize: pageParams.pageSize,
      ...config?.params
    };

    const response = await this.get(url, params, config);
    const { data, total = 0 } = response.data;

    return {
      data,
      total,
      page: pageParams.page,
      pageSize: pageParams.pageSize,
      totalPages: Math.ceil(total / pageParams.pageSize),
      hasNext: pageParams.page < Math.ceil(total / pageParams.pageSize),
      hasPrev: pageParams.page > 1
    };
  }
}

/**
 * 常用请求模板
 */
const COMMON_TEMPLATES = {
  // 用户相关
  USER_LOGIN: {
    name: 'USER_LOGIN',
    method: 'POST',
    url: '/api/auth/login',
    headers: { 'Content-Type': 'application/json' }
  },
  USER_REGISTER: {
    name: 'USER_REGISTER',
    method: 'POST',
    url: '/api/auth/register',
    headers: { 'Content-Type': 'application/json' }
  },
  USER_INFO: {
    name: 'USER_INFO',
    method: 'GET',
    url: '/api/user/info'
  },
  USER_UPDATE: {
    name: 'USER_UPDATE',
    method: 'PUT',
    url: '/api/user/update',
    headers: { 'Content-Type': 'application/json' }
  },

  // 文件相关
  FILE_UPLOAD: {
    name: 'FILE_UPLOAD',
    method: 'POST',
    url: '/api/file/upload',
    headers: { 'Content-Type': 'multipart/form-data' }
  },
  FILE_DOWNLOAD: {
    name: 'FILE_DOWNLOAD',
    method: 'GET',
    url: '/api/file/download',
    responseType: 'blob'
  },
  FILE_LIST: {
    name: 'FILE_LIST',
    method: 'GET',
    url: '/api/file/list'
  },

  // 数据相关
  DATA_LIST: {
    name: 'DATA_LIST',
    method: 'GET',
    url: '/api/data/list'
  },
  DATA_CREATE: {
    name: 'DATA_CREATE',
    method: 'POST',
    url: '/api/data/create',
    headers: { 'Content-Type': 'application/json' }
  },
  DATA_UPDATE: {
    name: 'DATA_UPDATE',
    method: 'PUT',
    url: '/api/data/update',
    headers: { 'Content-Type': 'application/json' }
  },
  DATA_DELETE: {
    name: 'DATA_DELETE',
    method: 'DELETE',
    url: '/api/data/delete'
  }
};

/**
 * 创建Axios客户端
 */
function createAxiosClient(config) {
  const client = new AxiosClient(config);

  // 添加常用模板
  Object.entries(COMMON_TEMPLATES).forEach(([name, template]) => {
    client.addTemplate(name, template);
  });

  // 添加默认拦截器
  client.addInterceptor({
    request: (config) => {
      // 添加认证token
      const token = localStorage.getItem('token');
      if (token) {
        config.headers = {
          ...config.headers,
          'Authorization': `Bearer ${token}`
        };
      }
      return config;
    },
    response: (response) => {
      // 处理响应数据
      if (response.data && response.data.code !== undefined) {
        if (response.data.code !== 0) {
          throw new Error(response.data.message || '请求失败');
        }
        response.data = response.data.data;
      }
      return response;
    },
    error: (error) => {
      // 处理错误
      if (error.status === 401) {
        localStorage.removeItem('token');
        window.location.href = '/login';
      }
      console.error('API请求错误:', error);
      throw error;
    }
  });

  return client;
}

/**
 * 快速Axios请求方法
 */
const axios = {
  /**
   * 创建Axios客户端
   */
  createClient: createAxiosClient,
  
  /**
   * 快速GET请求
   */
  get: async (url, params) => {
    const client = createAxiosClient();
    return client.get(url, params);
  },
  
  /**
   * 快速POST请求
   */
  post: async (url, data) => {
    const client = createAxiosClient();
    return client.post(url, data);
  },
  
  /**
   * 快速PUT请求
   */
  put: async (url, data) => {
    const client = createAxiosClient();
    return client.put(url, data);
  },
  
  /**
   * 快速DELETE请求
   */
  delete: async (url) => {
    const client = createAxiosClient();
    return client.delete(url);
  }
};

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = { AxiosClient, createAxiosClient, axios, COMMON_TEMPLATES };
} else if (typeof window !== 'undefined') {
  window.axios = axios;
  window.AxiosClient = AxiosClient;
  window.createAxiosClient = createAxiosClient;
  window.COMMON_TEMPLATES = COMMON_TEMPLATES;
}
